package binding

import (
	//"fmt"
	"gopkg.in/bluesuncorp/validator.v5"
	"reflect"
	"strings"
	"sync"
)

type defaultValidator struct {
	once     sync.Once
	validate *validator.Validate
}

var _ StructValidator = &defaultValidator{}

func (v *defaultValidator) ValidateStruct(obj interface{}) error {
	if kindOfData(obj) == reflect.Struct {
		v.lazyinit()
		trimStruct(obj)
		if err := v.validate.Struct(obj); err != nil {
			return error(err)
		}
	}
	return nil
}

func (v *defaultValidator) lazyinit() {
	v.once.Do(func() {
		v.validate = validator.New("binding", validator.BakedInValidators)
	})
}

func kindOfData(data interface{}) reflect.Kind {
	value := reflect.ValueOf(data)
	valueType := value.Kind()
	if valueType == reflect.Ptr {
		valueType = value.Elem().Kind()
	}
	return valueType
}

// trim space
func trimStruct(dst interface{}) {
	vv := reflect.ValueOf(dst)
	t := reflect.Indirect(vv).Type()
	v := vv.Elem()
	for i := 0; i < t.NumField(); i++ {
		if t.Field(i).Type.Kind() == reflect.String {
			v.Field(i).SetString(strings.TrimSpace(v.Field(i).String()))
		}
	}
}
